package xml;

import java.io.FileOutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import dataStructures.*;

import javax.xml.stream.*;
import javax.xml.stream.events.*;

@SuppressWarnings("restriction")
public class TweetWriter extends XMLWriter {
	
	public TweetWriter(String filenameTimeStamp) {
		super(filenameTimeStamp);
	}

	public void writeTweets(List<MyTweet> tweets) {
		try {
			// Create a XMLOutputFactory
			XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();
			// Create XMLEventWriter
			XMLEventWriter eventWriter = outputFactory.createXMLEventWriter(new FileOutputStream("data" + System.getProperty("file.separator") + filenameTimeStamp), "UTF-8");
			// Create a EventFactory
			XMLEventFactory eventFactory = XMLEventFactory.newInstance();
			XMLEvent end = eventFactory.createDTD("\n");
			// Create and write Start Tag
			StartDocument startDocument = eventFactory.createStartDocument();
			eventWriter.add(startDocument);
			//simply add a new line
			eventWriter.add(eventFactory.createCharacters("\n"));
			// Create config open tag
			StartElement configStartElement = eventFactory.createStartElement("","", "tweets");
			eventWriter.add(configStartElement);
			//simply add a new line
			eventWriter.add(eventFactory.createCharacters("\n"));
			//XMLEvent tab = eventFactory.createDTD("\t");
						
			for (MyTweet t : tweets) {
				StartElement tweetStartElement = eventFactory.createStartElement("","", "tweet");
				eventWriter.add(tweetStartElement);
	
				Attribute attribute = eventFactory.createAttribute("name", t.name);
				eventWriter.add(attribute);
				attribute = eventFactory.createAttribute("text", t.text);
				eventWriter.add(attribute);
				
				eventWriter.add(end);
				
				// Write the different nodes
				if (t.location != null) {
					Map<String, String> attributes = new HashMap<String, String>();
					attributes.put(Const.LATITUDE, t.location.latitude);
					attributes.put(Const.LONGITUDE, t.location.longitude);
					createNode(eventWriter, "location", "", attributes);
				}
				
				Map<String, String> attributes = new HashMap<String, String>();
				attributes.put("value", t.time);
				createNode(eventWriter, "time", "", attributes);
		
				eventWriter.add(eventFactory.createEndElement("", "", "tweet"));
				
				eventWriter.add(end);
			}
			eventWriter.add(eventFactory.createEndElement("", "", "tweets"));
			eventWriter.add(end);
			eventWriter.add(eventFactory.createEndDocument());
			eventWriter.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
